package com.itheima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.hmall.client.Feignclient;
import com.hmall.common.dto.PageDTO;
import com.hmall.common.pojo.Item;
import com.itheima.search.pojo.ItemDoc;
import com.itheima.search.pojo.RequestParams;
import com.itheima.search.service.SearService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.lucene.search.function.FunctionScoreQuery;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class SearchServiceImpl implements SearService {

    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private Feignclient feignclient;


    @Override
    public List<String> getSuggestions(String prefix) {

        try {
            // 1.准备Request
            SearchRequest request = new SearchRequest("item");
            // 2.准备DSL
            request.source().suggest(new SuggestBuilder().addSuggestion(
                    "suggestions",
                    SuggestBuilders.completionSuggestion("suggestion")
                            .prefix(prefix)
                            .skipDuplicates(true)
                            .size(10)
            ));
            // 3.发起请求
            SearchResponse response = null;
            response = client.search(request, RequestOptions.DEFAULT);
            // 4.解析结果
            Suggest suggest = response.getSuggest();
            // 4.1.根据补全查询名称，获取补全结果
            CompletionSuggestion suggestions = suggest.getSuggestion("suggestions");
            // 4.2.获取options
            List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
            // 4.3.遍历
            List<String> list = new ArrayList<>(options.size());
            for (CompletionSuggestion.Entry.Option option : options) {
                String text = option.getText().toString();
                list.add(text);
            }
            return list;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Map<String, List<String>> getFilers(RequestParams params) {
        SearchRequest request = new SearchRequest("item");
        SearchSourceBuilder source = request.source();

        buildBasicQuery(params, request);

        source.aggregation(AggregationBuilders.terms("category").field("category").size(20));
        source.aggregation(AggregationBuilders.terms("brand").field("brand").size(20));

        try {

            //执行查询
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //获取结果
            Aggregations aggregations = response.getAggregations();
            Terms terms = aggregations.get("category");

            Map<String, List<String>> result = new HashMap<>();

            List<String> category = getAggByName(aggregations, "category");
            List<String> brand = getAggByName(aggregations, "brand");

            result.put("category", category);
            result.put("brand", brand);

            return result;

        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;

    }

    @Override
    public PageDTO<ItemDoc> search(RequestParams params) {
        SearchRequest request = new SearchRequest("item");
        //SearchSourceBuilder source = request.source();

        buildBasicQuery(params, request);

        //分页
        Integer page = params.getPage();
        Integer size = params.getSize();
        request.source().from((page - 1) * size).size(size);

        //排序
        String sortBy = params.getSortBy();
        if ("sold".equals(sortBy)) {
            request.source().sort("sold", SortOrder.ASC);
        }
        if ("price".equals(sortBy)) {
            request.source().sort("price", SortOrder.ASC);
        }

        //高亮
        request.source().highlighter(new HighlightBuilder()
                .field("name")
                .requireFieldMatch(false)
        );

        try {

            //查询
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);

            SearchHits responseHits = response.getHits();
            //总条数
            long total = responseHits.getTotalHits().value;
            //结果数组
            SearchHit[] hits = responseHits.getHits();

            //结果存储容器
            List<ItemDoc> resourceList = new ArrayList<>();

            for (SearchHit hit : hits) {
                String json = hit.getSourceAsString();
                ItemDoc itemDoc = JSON.parseObject(json, ItemDoc.class);
                //处理高亮结果
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                if (!CollectionUtils.isEmpty(highlightFields)) {
                    HighlightField highlightField = highlightFields.get("name");
                    if (highlightField != null) {
                        String name = highlightField.getFragments()[0].toString();
                        itemDoc.setName(name);
                    }
                }
                resourceList.add(itemDoc);
            }

            //返回总条数、结果集
            return new PageDTO<>(total, resourceList);

        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public void itemStatusUp(Long id) {
        try {
            Item item = feignclient.queryById(id);
            // System.out.println(item);

            ItemDoc itemDoc = new ItemDoc(item);
            // System.out.println(itemDoc);

            IndexRequest indexRequest = new IndexRequest("item");
            indexRequest.id(String.valueOf(item.getId()));

            indexRequest.source(JSON.toJSONString(itemDoc), XContentType.JSON);
            log.info("前台上架商品：ID{}",item.getId());
            client.index(indexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Override
    public void itemStatusDow(Long id) {
        try {
            DeleteRequest deleteRequest = new DeleteRequest("item", String.valueOf(id));
            log.info("前台下架商品：ID{}",id);
            client.delete(deleteRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }




    private List<String> getAggByName(Aggregations aggregations, String aggName) {
        Terms terms = aggregations.get(aggName);

        ArrayList<String> brandList = new ArrayList<>();
        List<? extends Terms.Bucket> buckets = terms.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            String key = bucket.getKeyAsString();
            brandList.add(key);
        }
        return brandList;
    }

    private void buildBasicQuery(RequestParams params, SearchRequest request) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //关键字
        String key = params.getKey();
        if (StringUtils.isNoneBlank(key)) {
            boolQuery.must(QueryBuilders.matchQuery("all", key));
        } else {
            boolQuery.must(QueryBuilders.matchAllQuery());
        }

        //分类
        String category = params.getCategory();
        if (StringUtils.isNoneBlank(category)) {
            boolQuery.must(QueryBuilders.termQuery("category", category));
        }

        //品牌
        String brand = params.getBrand();
        if (StringUtils.isNoneBlank(brand)) {
            boolQuery.must(QueryBuilders.termQuery("brand", brand));
        }

        request.source().query(boolQuery);

        //  价格
        //最大价格
        Integer maxPrice = params.getMaxPrice();
        //最小价格
        Integer minPrice = params.getMaxPrice();
        if (maxPrice != null && minPrice != null) {
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(minPrice).lte(maxPrice));
        }

        //竞价排名
        FunctionScoreQueryBuilder builder = QueryBuilders.functionScoreQuery(
                //原始 相关性
                boolQuery,
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                //过滤条件
                                QueryBuilders.termQuery("isAD", true),
                                // 修改 原生分数乘10
                                ScoreFunctionBuilders.weightFactorFunction(10)

                        )
                }
                //设置加权方式
        ).scoreMode(FunctionScoreQuery.ScoreMode.MULTIPLY);
        request.source().query(builder);
        //request.source().query(boolQuery);

    }

    private void buildAggregation(SearchRequest request) {
        request.source().aggregation(AggregationBuilders
                .terms("categoryAgg")
                .field("category")
                .size(100)
        );
        request.source().aggregation(AggregationBuilders
                .terms("brandAgg")
                .field("brand")
                .size(100)
        );
    }
}
